Ext.define('App.view.common.file.FileField', {
	extend: 'Ext.form.field.File',
	xtype: 'commonFileField',
	fieldLabel: '附件 ',
	labelWidth: 50,
	readOnly: false,
	isMultiple: false,//是否支持多附件选择
	accept:"",//过滤文件类型 "application/zip,text/xml,image/*",
    regex: /(txt)|(pdf)|(jpg)|(png)|(doc)|(docx)|(xls)|(xlsx)|(zip)|(rar)|(JPG)|(PNG)|(ppt)|(pptx)$/i,
    regexText: '仅能上传txt、pdf、jpg、png、zip、 doc、docx、xls和xlsx格式的文件',
	buttonConfig:{
		text: '选择文件',
		iconCls: 'fa fa-file-o fa-lg'
	},
	initComponent: function(){
		this.callParent();
	},
	
	supportMultFn: function(th) {

		//2.1 为input添加支持多文件选择属性

		//var typeArray = ["application/zip", "text/*", "image/*"];

		var fileDom = th.getEl().down('input[type=file]');

		fileDom.dom.setAttribute("multiple", "multiple");

		fileDom.dom.setAttribute("accept",this.accept);

	},

	/*获取多附件文件信息示例
	listeners: {
		change: function() {

			var grid = this.up('window').grid;

			//2.3 获取文件列表

			var fileDom = this.getEl().down('input[type=file]');

			var files = fileDom.dom.files;

			var fileArr = [];

			for (var i = 0; i < files.length; i++) {

				fileArr.push({

					fileName: files[i].name,

					fileSize: files[i].size / 1024 + "KB",

					upDate: new Date()

				});

				//  fileArr.push((i+1)+"、文件名："+files[i].name+",类型:"+files[i].type+",大小:"+files[i].size/1024+"KB");

			}

			grid.getStore().loadData(fileArr);
			//2.4 选择完后input会还原，所以还需要再次重写

			this.supportMultFn(this);

		}

	}*/

	listeners: {
		afterrender: function() {
			if(this.isMultiple){
				this.supportMultFn(this);
			}
		},
	    change: function ( fileField, newValue, oldValue ) {
            //取控件DOM对象
            var field = document.getElementById(fileField.getId());
            //取控件中的input元素
            var inputs = field.getElementsByTagName('input');
            var fileInput = null;
            var il = inputs.length;
            //取出input 类型为file的元素
            for(var i = 0; i < il; i ++){
                if(inputs[i].type == 'file'){
                    fileInput = inputs[i];
                    break;
                }
            }
            if(fileInput != null){
                var fileSize = fileField.getFileSize(fileInput);
                //允许上传不大于20M的文件
                if(fileSize > 20971520){
                    Ext.Msg.alert('提示','附件只能上传小于20M！');
                    fileField.reset();
                }
            }
		}

		,validitychange: function(file, isValid, eOpts){
            var borderColor = '#cfcfcf';
            if(!isValid){
                borderColor = '#cf4c35';
            }

		    var commonFileFieldExp = file.up("commonFileFieldExp");
		    if(!Ext.isEmpty(commonFileFieldExp) && "commonFileFieldExp" === commonFileFieldExp.getXType()){
                var fileName = commonFileFieldExp.down("container[name=attName]");
                fileName.setStyle({borderColor:borderColor, borderWidth:'1px',borderStyle:'solid'});
            }else {
                file.setFieldStyle({'border-color':borderColor});
            }
        }
	},


    /**
     * 获取文件大小
     * @param target input类型为file的元素
     * return fs 返回文件的大小（单位byte）
     */
    getFileSize : function(target) {
        var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
        var fs = 0;
        if (isIE && !target.files) {
            var filePath = target.value;
            var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
            var file = fileSystem.GetFile (filePath);
            fs = file.Size;
        }else if(target.files && target.files.length > 0){
            fs = target.files[0].size;
        }else{
            fs = 0;
        }

        return fs;
    },
    /**
     * 获取附件数据
     * @param id 当前数据id
     * @param attIdentify 当前附件标识
     * @returns {string} 附件对象数量JSON
     */
    findAttByIdAndIdentify:function (id,attIdentify) {
        var retdata='';
        Ext.Ajax.request({
            url: "sqm/base/findAttachNameFile",
            params: {id: id,attIdentify:attIdentify},
            async:false,
            method: 'GET',
            success: function (response) {
                var data = response.responseText;
                if(data){
                    retdata = Ext.decode(data);
                }


            }
        });
        return retdata;
    },
    /**
     * 创建装附件容器
     * @param attId  附件id容器名称
     * @param attName 附件名称容器
     * @param htmeText 附件标题
     */
    createItme:function (attId,attName,htmeText) {
        var item=Ext.create({
            layout:'hbox',
            xtype:'container',
            name: 'attachmentcontainer',
            margin:'5 0 0 0',
            fullscreen: true,
            items:[{
                layout:'hbox',
                flex: 2,
                items: [{
                    xtype: "hidden",
                    name: attId
                }, {
                    style: {'text-align': 'right'},

                    items: [{
                        minWidth: 105,
                        name: 'htmlTextTitle',
                        html: "<span style='color:#666'>"+htmeText+"</span>"+" :"

                    }]
                }, {
                    items: [{
                        xtype: 'panel',
                        name: attName
                    }]
                }]
            }]
        });
        return item;
    },
    /**
     * 附件下载连接
     * @param cmpForm 当前附件所在的form 对象
     * @param data 附件数据
     * @param attName  附件容器名称
     * @param attId 附件容器id
     */
    downloadAtt:function (cmpForm,data,attName,attId) {
        var fileName = cmpForm.down("panel[name="+attName+"]");
        if(fileName){
            fileName.removeAll();
            if (data=='') {
                fileName.add({html: "附件为空！"});
            } else {
                var id = data.id;
                var name = data.attName;
                var path = "sqm/base/downloadFile?id=" + id;
                fileName.add({html: "<a href='" + path + "' ><i class='fa fa-cloud-download' aria-hidden='false'></i>" + name + "</a>"});
                cmpForm.down("hidden[name="+attId+"]").setValue(id);
            }
        }
    }
});